<template>
	<view class="my" style="padding-top: 20rpx;">
		<!-- 		<view class="bg">

		</view>
		<view class="border">

		</view> -->
		<u-datetime-picker :show="show4" v-model="value1" mode="datetime" :minDate="min" @confirm="confirm"
			@cancel="show4=false"></u-datetime-picker>
		<view class="tab-box" style="display: flex;align-items: center;justify-content: space-between;">
			<view :class="service==1?'active':'tab'" @click="service=1">
				到店安装
			</view>
			<view :class="service==2?'active':'tab'" @click="service=2">
				上门安装
			</view>
		</view>
		<view class="header">
			<view class="top" @click="chooseAddress" v-if="service==2">
				<image src="../../static/img/tip2.png" mode="widthFix"></image>
				<view class="detial" v-if="chooseItem.id">
					<view class="area" style="font-weight: 600;font-size: 34rpx;">
						<view class="">
							{{chooseItem.province}}/{{chooseItem.city}}/{{chooseItem.area}} {{chooseItem.detail}}
						</view>
					</view>
					<view class="" style="color: #7F7F7F;font-size: 26rpx;margin-top: 20rpx;">
						{{chooseItem.username}} | {{chooseItem.mobile}}
					</view>
				</view>
				<view v-if="!chooseItem.id">
					选择上门地址
				</view>

			</view>
			<view class="top" v-else>
				<image src="../../static/img/tip2.png" mode="widthFix"></image>
				<view class="detial" v-if="shopList.length>0">
					<view class="area" style="font-weight: 600;font-size: 34rpx;">
						<view class="">
							{{shopList[0].address}}
						</view>
					</view>
					<view class="" style="color: #7F7F7F;font-size: 26rpx;margin-top: 20rpx;">
						{{shopList[0].name}} <text
							style="color: #75D65E;font-size: 24rpx;margin-left: 10rpx;">(距离{{shopList[0].distance}}km)</text>
					</view>
				</view>
				<view v-else>
					正在加载最近门店
				</view>

			</view>
			<view class="items" style="padding-top: 1rpx;">
				<!-- 			<view class="title"
					style="color: #3E5170;margin: 30rpx;margin-bottom: 0;display: flex;align-items: center;">
					<image src="../../static/img/tip1.png" mode=""
						style="width: 30rpx;margin-right: 10rpx;height: 30rpx;">
					</image>
					{{shopName}}
				</view> -->
				<view class="item">
					<image :src="'https://ba.fuliaoxx.com'+info.images.split(',')[0]" mode="" mode="good"></image>
					<view class="detail">
						<view class="name" style="display: flex;align-items: center;">
							{{info.name}}
						</view>
						<view class=""
							style="color: #3E5170;background-color: #F7F6F6;width: 140rpx;text-align: center;padding: 10rpx 0;font-size: 24rpx;border-radius: 8rpx;">
							数量：{{num}}
						</view>
						<view class="num">
							<view class="" style="color: #FC5D2B;font-weight: 600;font-size: 32rpx;">
								￥{{price}}
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="mask-box" style="display: flex;align-items: center;justify-content: space-between;"
				@click="show2=true">
				<view class="">
					优惠券
				</view>
				<u-icon name="arrow-right" v-if="!nowCop.id"></u-icon>
				<view class="" v-else>
					{{nowCop.name}}
				</view>
			</view>
			<view class="mask-box" style="display: flex;align-items: center;justify-content: space-between;"
				@click="show4=true">
				<view class="">
					预约时间
				</view>
				<u-icon name="arrow-right" v-if="!value1"></u-icon>
				<view class="" v-else>
					{{timestampToDatetime(value1)}}
				</view>
			</view>
			<view class="mask-box">
				<!-- 				<view class="" style="margin-bottom: 30rpx;">
					服务方式
				</view>
				<view class="">
					<u-radio-group v-model="check">
						<u-radio activeColor="#75D65E" label="到店" :name="1"></u-radio>
						<view class="" style="width: 40rpx;">

						</view>
						<u-radio activeColor="#75D65E" label="配送" :name="2"></u-radio>
					</u-radio-group>
				</view> -->

				<view class="">
					备注
				</view>
				<u--textarea border="none" placeholder="请输入备注内容" v-model="mask"></u--textarea>
			</view>
		</view>
		<view class="footer">
			<view class="num" style="color: #3E5170;">
				实付款:
				<text style="color: #FF4E31;font-size: 38rpx;font-weight: 600;">￥{{totalPrice}}</text>
			</view>
			<view class="btn" @click="buy">
				提交订单
			</view>
		</view>
		<u-popup :show="show" @close="show=false">
			<view class="box" style="position: relative;">
				<view style="height: calc(100% - 150rpx);overflow: auto;">
					<view class="item2" v-for="(item,index) in lists" :key="index" @click.stop="choose(item)">
						<view class="icon" v-if="chooseItem.id==item.id">
							<u-icon name="checkbox-mark" color="#75D65E" size="24"></u-icon>
						</view>
						<view style="display: flex;align-items: center;">
							<text v-if="item.is_default"
								style="padding: 4rpx 10rpx;color: white;background-color: #75D65E;margin-right: 10rpx;border-radius: 10rpx;">默认</text>
							{{item.province}}/{{item.city}}/{{item.area}}/{{item.detail}}
						</view>
						<view class="">
						</view>
						<view style="display: flex;align-items: center;justify-content: space-between;">
							<view>
								<text>{{item.username}}</text>
								<text>{{item.mobile}}</text>
							</view>
							<!-- 			<view style="display: flex;align-items: center;">
								<view @click.stop="edit(item)" style="margin-right: 12rpx;">
									<u-icon name="edit-pen" color="#9e9e9e" size="20"></u-icon>
								</view>
								<view class="" @click.stop="delAdd(item.id)">
									<u-icon name="trash" color="#9e9e9e" size="20"></u-icon>
								</view>
							</view> -->
						</view>
					</view>
				</view>
				<view class="btn-box">
					<view class="btn" @click="add">
						新增上门地址
					</view>
				</view>
			</view>
		</u-popup>
		<u-popup :show="show2" @close="show2=false">
			<view class="box" style="position: relative;overflow: auto;">
				<!-- <u-modal :show="show3" title="优惠券详情" :content='content' @confirm="show3=false"></u-modal> -->

				<u-modal :show="show3" title="优惠券详情" @confirm="show3=false">
					<view class="slot-content" style="height: 60vh;overflow: auto;">
						{{content}}
					</view>
				</u-modal>
				<view class="coupon-list" v-if="couponsList.length > 0">
					<view class="item acea-row row-center-wrapper" v-cloak v-for="(item, index) in couponsList"
						:key="index" style="border-radius: 10rpx;overflow: hidden;">
						<view class="money moneyGray" :class="item._type === 0 ? 'moneyGray' : ''"
							style="background-color: red;">
							<view>
								￥<span class="num">{{item.price}}</span>
							</view>
							<view class="pic-num">{{item.name}}</view>
						</view>
						<view class="text">
							<view class="condition line1">
								{{item.intro}}
							</view>
							<view class="data acea-row row-between-wrapper" style="align-items: center;">
								<view>{{formatTimestamp(item.createtime)}}</view>
								<!-- <view v-else>{{ item.createTime }}-{{ item.endTime }}</view> -->
								<view class="" style="display: flex;">
									<view class="bnt gray" @click="showCop(item)" style="margin-right: 12rpx;">详情</view>
									<view class="bnt" style="background-color: red;" @click="chooseCop(item)"
										v-if="!nowCop.id">选择</view>
									<view class="bnt gray" @click="chooseCop({})" v-if="nowCop.id==item.id">取消</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<!--暂无优惠券-->
				<view class="noCommodity" v-if="couponsList.length === 0">
					<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png" text="暂时没有可用的优惠券">
					</u-empty>
				</view>
			</view>
		</u-popup>
		<view class="" style="height: 160rpx;">

		</view>
	</view>
</template>

<script>
	import {
		list4
	} from "@/request/api/coupon.js"
	import {
		getShop
	} from "@/request/api/home.js"
	import {
		list1,
		list,
		getType,
		createOrder1
	} from "@/request/api/goods.js"
	import {
		list3,
		del
	} from "@/request/api/address.js"

	export default {
		data() {
			return {
				// fileList: [],
				// car: [],
				content: '',
				couponsList: [],
				show3: false,
				content: '',
				couponsList: [],
				show: false,
				show2: false,
				show4: false,
				lists: [],
				value1: '',
				min: "",
				mask: "",
				check: 1,
				service: 1,
				info: {

				},
				shopName: "",
				totalPrice: 0,
				num: 0,
				nowCop: {},
				chooseItem: {
					id: null
				},
				shopList: [],
				price: 0,
				spec_id: null,
				old_new: 0
			}
		},
		async onShow() {
			let now = new Date();

			// 获取当前小时和分钟
			let hours = now.getHours();
			let minutes = now.getMinutes();

			// 判断条件
			let targetDate;

			// 如果当前时间大于21:00
			if (hours >= 21) {
				// 获取第二天的早上9点时间戳
				targetDate = new Date(now);
				targetDate.setDate(now.getDate() + 1); // 设置为第二天
				targetDate.setHours(9, 0, 0, 0); // 设置为早上9点
			}
			// 如果当前时间小于9:00
			else if (hours < 9) {
				// 获取今天的早上9点时间戳
				targetDate = new Date(now);
				targetDate.setHours(9, 0, 0, 0); // 设置为早上9点
			}
			// 否则，正常获取当前时间戳
			else {
				targetDate = now;
			}

			// 获取目标时间的时间戳
			let timestamp = targetDate.getTime();

			this.min = timestamp;
			this.chooseItem = {
				id: null
			}
			let res = await list3({});
			this.lists = res.data;
		},

		async onLoad(opt) {
			let that = this;
			this.info = JSON.parse(opt.item);

			this.num = Number(opt.num);
			this.price = Number(opt.price);
			this.old_new = Number(opt.old_new);
			this.spec_id = Number(opt.spec_id);
			// this.shopName = opt.shopName;
			this.totalPrice = this.price * this.num;
			let location = uni.getStorageSync('location')
			if (!location) {
				uni.getSetting({
					success(res) {
						console.log(res)
						if (res.authSetting['scope.userLocation']) {
							// 用户已经授权
							console.log('用户已授权定位');
							// 在这里可以调用需要定位权限的API
							uni.getLocation({
								type: 'gcj02',
								geocode: true,
								success: async function(res) {
									console.log(res)
									let location1 = {
										lat: res.latitude,
										lng: res.longitude
									}
									uni.setStorageSync("location", location1)

									let shopRes = await getShop({
										goods_id: that.info.id,
										...location1
									})
									that.shopList = shopRes.data;
									let res2 = await list4({
										product_id: that.info.id,
										status: 1
									});
									that.couponsList = res2.data;
								},
								fail: function(res) {
									uni.showToast({
										title: "获取当前定位失败",
										icon: "none"
									})
								}
							});
						} else {
							// 用户未授权
							console.log('用户未授权定位');
							uni.authorize({
								scope: 'scope.userLocation',
								success() {
									console.log('授权成功');
									// 可以在这里调用需要定位权限的API
									uni.getLocation({
										type: 'gcj02',
										geocode: true,
										success: async function(res) {
											console.log(res)
											let location1 = {
												lat: res.latitude,
												lng: res.longitude
											}
											uni.setStorageSync("location", location1)

											let shopRes = await getShop({
												goods_id: that.info.id,
												...location1
											})
											that.shopList = shopRes.data;
											let res2 = await list4({
												product_id: that.info.id,
												status: 1
											});
											that.couponsList = res2.data;
										},
										fail: function(res) {
											uni.showToast({
												title: "获取当前定位失败",
												icon: "none"
											})
										}
									});
								},
								fail() {
									console.log('授权失败');
									// 可以在这里提示用户手动去设置中开启定位权限
								}
							});
							// 提示用户进行授权
						}
					}
				});
				return
			}
			let shopRes = await getShop({
				goods_id: this.info.id,
				...location
			})
			console.log(shopRes)
			this.shopList = shopRes.data;
			let res = await list4({
				product_id: this.info.id,
				status: 1
			});
			this.couponsList = res.data;

		},
		methods: {
			confirm(e) {
				this.value1 = e.value;
				this.show4 = false;
			},
			roundUpToTwoDecimalPlaces(num) {
				return Math.ceil(num * 100) / 100;
			},
			timestampToDatetime(timestamp) {
				let date = new Date(timestamp);
				// 获取年、月、日、时、分、秒
				let year = date.getFullYear();
				let month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从 0 开始的，所以要加 1
				let day = ('0' + date.getDate()).slice(-2);
				let hours = ('0' + date.getHours()).slice(-2);
				let minutes = ('0' + date.getMinutes()).slice(-2);
				let seconds = ('0' + date.getSeconds()).slice(-2);
				// 返回格式化的时间字符串
				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},
			chooseCop(item) {
				if (item.price) {
					let tot = this.roundUpToTwoDecimalPlaces(this.totalPrice - item.price);
					if (tot < 0) {
						tot = 0
					}
					this.totalPrice = tot

				} else {
					this.totalPrice = this.info.price * this.num;
				}
				this.nowCop = item;
				this.show2 = false;
			},
			formatTimestamp(timestamp) {
				// 创建 Date 对象
				const date = new Date(timestamp * 1000); // 将时间戳转换为毫秒
				// 获取年份、月份、日期、小时、分钟、秒
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
				const day = String(date.getDate()).padStart(2, '0');
				const hour = String(date.getHours()).padStart(2, '0');
				const minute = String(date.getMinutes()).padStart(2, '0');
				const second = String(date.getSeconds()).padStart(2, '0');
				// 返回格式化的日期时间字符串
				return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
			},
			showCop(item) {
				this.content = item.intro;
				this.show3 = true;
			},
			async buy() {
				uni.showLoading({
					mask: true
				})
				if (this.service == 2 && !this.chooseItem.id) {
					uni.showToast({
						icon: "none",
						title: "请选择上门地址"
					})
					return
				}
				if (!this.value1) {
					uni.showToast({
						icon: "none",
						title: "请选择预约时间"
					})
					return
				}
				let params = {
					product_id: this.info.id,
					spec_id: this.spec_id,
					address_id: this.chooseItem.id,
					num: this.num,
					service: this.service,
					shop_id: this.shopList[0].id,
					remark: this.mask,
					price: this.price,
					old_new: this.old_new,
					appionttime: parseInt(this.value1 / 1000)
				}
				if (this.nowCop.id) {
					params['quan_id'] = this.nowCop.id;
				}
				let res = await createOrder1(params);
				console.log(res)
				if (res.code == 1) {
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: res.data.timeStamp,
						nonceStr: res.data.nonceStr,
						package: res.data.package,
						signType: res.data.signType,
						paySign: res.data.paySign,
						success: function(res) {
							uni.hideLoading()
							uni.reLaunch({
								url: "/pages/myOrders2/myOrders"
							})
						},
						fail: function(err) {
							console.log(err);
							uni.hideLoading()
						}
					})

				}
			},
			add() {
				uni.navigateTo({
					url: "/pages/addressAdd/addressAdd"
				})
			},
			choose(item) {
				this.chooseItem = item;
			},
			async delAdd(id) {
				await del(id)
				if (this.chooseItem.id == id) {
					this.chooseItem = {}
					return
				}
				let res = await list();
				this.lists = res.data.data;
			},
			edit(item) {
				uni.navigateTo({
					url: "/pages/addressAdd/addressEdit?item=" + JSON.stringify(item)
				})
			},
			chooseAddress() {
				if (this.lists.length == 0) {
					uni.navigateTo({
						url: "/pages/addressAdd/addressAdd"
					})
					return
				}
				this.show = true;
			}
		}
	}
</script>

<style>
	page {
		height: 100%;
		background-color: #F0F3F7;
	}
</style>
<style scoped lang="scss">
	.bnt {
		width: 80rpx !important;
	}

	.tab-box {
		margin-top: 20rpx;
		border-radius: 30rpx;
		background-color: white;
		box-sizing: border-box;
		margin: 30rpx;

		.tab {
			flex: 1;
			text-align: center;
			padding: 30rpx;
		}

		.active {
			flex: 1;
			background-color: #75D65E;
			color: white;
			text-align: center;
			padding: 30rpx;
			border-radius: 30rpx;
		}
	}

	/deep/ .line {
		input {
			text-align: right !important;
		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		background-color: white;
		width: 100%;
		display: flex;
		box-sizing: border-box;
		padding: 30rpx;
		z-index: 99;

		.num {
			display: flex;
			align-items: center;
			flex: 2;
			display: flex;
			padding-left: 30rpx;
			font-size: 26rpx;
		}

		.btn {
			width: 240rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background: linear-gradient(to right, #75D65E, #75D65E);
			padding: 20rpx 0;
			border-radius: 100px;
		}
	}

	.my {
		height: 100%;
		box-sizing: border-box;

		.bg {
			position: fixed;
			width: 100%;
			height: 180rpx;
			top: 0;
		}

		.border {
			position: fixed;
			width: 100%;
			background-color: #F8F8F8;
			height: 80rpx;
			top: 120rpx;
			z-index: 1;
			border-radius: 50rpx 50rpx 0 0;
		}

		.header {
			position: relative;
			z-index: 1;
			margin: 0 30rpx;
			box-sizing: border-box;
			// height: calc(100% - 200rpx);


			image {
				width: 40rpx;
				margin-right: 16rpx;
			}

			.top {
				position: relative;
				border-radius: 30rpx;
				background-color: white;
				padding: 30rpx;

				display: flex;
				align-items: center;


				.detial {
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.area {
						display: flex;
						align-items: center;
						font-size: 28rpx;

						.tip {
							background-color: #FBDB0C;
							padding: 6rpx 10rpx;
							margin-right: 20rpx;
							border-radius: 10rpx;
						}
					}
				}
			}

			.mask-box {
				margin-top: 20rpx;
				padding: 30rpx;
				border-radius: 30rpx;
				background-color: white;
				box-sizing: border-box;
			}

			.items {
				margin-top: 20rpx;
				border-radius: 30rpx;
				background-color: white;
				box-sizing: border-box;

				.item {
					display: flex;
					padding: 30rpx;

					image {
						width: 180rpx;
						height: 180rpx;
						border-radius: 10rpx;
						margin-right: 20rpx;
					}

					.detail {
						height: 180rpx;
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						flex: 1;
						padding: 6rpx 0;
						box-sizing: border-box;

						.num {
							display: flex;
							justify-content: space-between;
							align-items: center;
						}
					}
				}
			}




		}



	}

	.box {
		overflow: auto;
		height: 700rpx;
	}

	.item2 {
		padding: 20rpx;
		border-bottom: 1rpx solid #dedede;
		position: relative;
		font-size: 24rpx;

		.icon {
			position: absolute;
			right: 20rpx;
			top: 20%;
			color: #75D65E;
			font-size: 30rpx;
		}
	}

	.btn-box {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;

		.btn {
			margin: 30rpx;
			margin-top: 100rpx;
			background: linear-gradient(to right, #75D65E, #75D65E);
			color: white;
			border-radius: 50px;
			text-align: center;
			padding: 24rpx 0;
			font-size: 32rpx;
		}
	}
</style>